﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
   public class Classes
    {
       DbHelper dbHelper = null;
       public Classes()
       {
           dbHelper = new DbHelper();
       }
        public void SetDr2Model(DataRow dr, MODEL.Classes model)
        {
            if (dr["CID"].ToString() != "")
            {
                model.CID = int.Parse(dr["CID"].ToString());
            }
            if (dr["CGID"].ToString() != "")
            {
                model.CGID = int.Parse(dr["CGID"].ToString());
                new DAL.Grades().SetDr2Model(dr, model.CGrade);//装填外键实体(年级)
            }
            model.CName = dr["CName"].ToString();
            if (dr["CCount"].ToString() != "")
            {
                model.CCount = int.Parse(dr["CCount"].ToString());
            }
            if (dr["CIsDel"].ToString() != "")
            {
                model.CIsDel = bool.Parse(dr["CIsDel"].ToString());
            }
            if (dr["CAddtime"].ToString() != "")
            {
                model.CAddtime = DateTime.Parse(dr["CAddtime"].ToString());
            }
        }

        #region 根据查询条件 返回 列表
        /// <summary>
        /// 根据查询条件 返回 列表
        /// </summary>
        /// <param name="paras"></param>
        /// <returns></returns>
        public List<MODEL.Classes> QueryListByCondition(SqlParameter[] paras)
        {
            MODEL.Classes model = null;
            StringBuilder sbSql = new StringBuilder("select * from Classes,Grades where CGID=GID and CIsDel=0 ");
            if (paras != null)
            {
                for (int i = 0; i < paras.Length; i++)//循环所有参数
                {
                    SqlParameter p = paras[i];
                    sbSql.Append(" and ");//第二个参数开始 在前面加 and
                    sbSql.Append(p.ParameterName.Substring(1));
                    sbSql.Append("=" + p.ParameterName);
                }
            }
            //读取数据库 返回查询到的数据表
            DataTable dt = (paras == null) ? dbHelper.GetDataTable(sbSql.ToString()) : dbHelper.GetDataTable(sbSql.ToString(), paras);
            //准备要返回的泛型集合
            List<MODEL.Classes> list = null;
            if (dt.Rows.Count > 0)//如果查询到的行数大于0
            {
                list = new List<MODEL.Classes>();
                foreach (DataRow dr in dt.Rows)
                {
                    model = new MODEL.Classes();
                    SetDr2Model(dr, model);
                    list.Add(model);
                }
            }
            return list;
        } 
        #endregion
    }
}
